package net.loyin.app.icp;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.jfinal.render.*;
import net.loyin.annotation.CtrlMethod;
import net.loyin.app.ctrl.front.FrontBaseCtrl;
import org.apache.log4j.Logger;

import java.util.Date;

/**
 * 前端拦截器
 * Created by loyin on 16/1/12.
 */
public class FrontInterceptor implements Interceptor {
    private static Logger logger = Logger.getLogger(FrontInterceptor.class);
    /**
     * 前端模板路径
     */
    public static String front_template;

    @Override
    public void intercept(Invocation invocation) {
        if (front_template == null) {
            front_template = PropKit.get("jfinal.template.front.dir") + PropKit.get("jfinal.template.front");
        }
        FrontBaseCtrl ctrl = (FrontBaseCtrl) invocation.getController();
        String ctrKey = invocation.getControllerKey();
        String method = invocation.getMethodName();
        String view = front_template + ctrKey + (ctrKey.endsWith("/") ? "" : "/") + method + ".html";
        CtrlMethod ctrlMethod = (CtrlMethod) invocation.getMethod().getAnnotation(CtrlMethod.class);
        Date now=new Date();
        ctrl.setAttr("nowtime",now.getTime());
        ctrl.setAttr("now",now);
        boolean needRender = true;//是否需要重新render
        if (ctrlMethod != null) {
            //是否是ajax访问 用户登录超时提示 json
            if (ctrlMethod.isAjax()) {
                needRender = false;
            }
        }
        invocation.invoke();
        Render render = ctrl.getRender();
        if (needRender) {
            if (render == null) {//当CTRL的method里没有render时执行转换到对应的view
                ctrl.render(view);
            } else {
                if ((render instanceof JsonRender) ||
                        (render.getClass().getSimpleName().endsWith("ActionRender")) ||
                        (render instanceof FileRender) ||
                        (render instanceof CaptchaRender) ||
                        (render instanceof ErrorRender) ||
                        (render instanceof FileRender) ||
                        (render instanceof IErrorRenderFactory) ||
                        (render instanceof IMainRenderFactory) ||
                        (render instanceof IXmlRenderFactory) ||
                        (render instanceof JavascriptRender) ||
                        (render instanceof JsonRender) ||
                        (render instanceof JspRender) ||
                        (render instanceof NullRender) ||
                        (render instanceof Redirect301Render) ||
                        (render instanceof RedirectRender) ||
                        (render instanceof TextRender) ||
                        (render instanceof XmlRender)) {

                } else {//视图渲染
                    render.setView(front_template + ctrKey + (ctrKey.endsWith("/") ? "" : "/") + render.getView() + ".html");
                }
            }
        }
    }
}
